home *** CD-ROM | disk | FTP | other *** search
/ FishMarket 1.0 / FishMarket v1.0.iso / fishies / 076-100 / disk_077 / samples / matrix.d < prev    next >
Text File  |  1992-05-06  |  2KB  |  82 lines

  1. /*
  2.  * matrixPrint - print out an integer matrix, together with a heading.
  3.  */
  4.  
  5. proc matrixPrint(*char message; [*, *] int m)void:
  6.     int i, j;
  7.  
  8.     writeln(message);
  9.     writeln();
  10.     for i from 0 upto dim(m, 1) - 1 do
  11.     for j from 0 upto dim(m, 2) - 1 do
  12.         write(m[i, j] : 5);
  13.     od;
  14.     writeln();
  15.     od;
  16.     writeln();
  17. corp;
  18.  
  19. /*
  20.  * matrixMultiply - multiply the first argument matrix by the second
  21.  *            argument matrix, leaving the result in the third.
  22.  *            Return 'true' if all is well, else return 'false' if
  23.  *            the passed matrixes aren't compatible.
  24.  */
  25.  
  26. proc matrixMultiply([*, *] int x; [*, *] int y; [*, *] int z)bool:
  27.     int i, j, k, sum;
  28.  
  29.     if dim(x, 2) ~= dim(y, 1) or dim(x, 1) ~= dim(z, 1) or
  30.         dim(y, 2) ~= dim(z, 2) then
  31.     /* the passed arrays don't fit in terms of size, return 'false'
  32.        to indicate failure */
  33.     false
  34.     else
  35.     for i from 0 upto dim(z, 1) - 1 do
  36.         for j from 0 upto dim(z, 2) - 1 do
  37.         sum := 0;
  38.         for k from 0 upto dim(x, 2) - 1 do
  39.             sum := sum + x[i, k] * y[k, j];
  40.         od;
  41.         z[i, j] := sum;
  42.         od;
  43.     od;
  44.     /* return 'true' to indicate that the arrays were compatible and the
  45.        multiplication has been done. */
  46.     true
  47.     fi
  48. corp;
  49.  
  50. /*
  51.  * main - this is the main program. Execution starts here.
  52.  */
  53.  
  54. proc main()void:
  55.     int M = 3, N = 6, P = 15;        /* the sizes for the arrays */
  56.     int i, j, k;
  57.     [M, N] int a;
  58.     [N, P] int b;
  59.     [M, P] int c;
  60.  
  61.     /* initialize the first matrix, 'a': */
  62.     for i from 0 upto M - 1 do
  63.     for j from 0 upto N - 1 do
  64.         a[i, j] := j - i;
  65.     od;
  66.     od;
  67.     matrixPrint("Matrix a:", a);
  68.     /* initialize the second matrix, 'b': */
  69.     for i from 0 upto N - 1 do
  70.     for j from 0 upto P - 1 do
  71.         b[i, j] := i - j;
  72.     od;
  73.     od;
  74.     matrixPrint("Matrix b:", b);
  75.     /* multiply the matrixes and print the result: */
  76.     if matrixMultiply(a, b, c) then
  77.     matrixPrint("Product matrix c:", c);
  78.     else
  79.     writeln("Error return from 'matrixMultiply'.");
  80.     fi;
  81. corp;
  82.